package com.lfsenior.queue;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * Created by dlupan on 2018/10/31
 */
public class QueueSenders {
    // TCP 地址
    public static final String BROKER_URL="tcp://localhost:61616";
    // 目标
    public static final String DESTINATION="QUEUE-QUEUE";

    /**
     * 发送消息
     * @param session
     * @param sender
     */
    public static void sendMessage(QueueSession session, QueueSender sender) throws Exception{
        for(int i=0;i<5;i++){
            String message = "发送消息第" + (i + 1) + "条";
            MapMessage map = session.createMapMessage();
            map.setString("text",message);
            map.setLong("time",System.currentTimeMillis());
            System.out.println(map);

            sender.send(map);
        }
    }

    public static void run() throws Exception{
        // 连接工厂
        QueueConnectionFactory factory = new ActiveMQConnectionFactory(BROKER_URL);
        // 创建连接
        QueueConnection connection = factory.createQueueConnection();
        // 启动连接
        connection.start();
        // 创建session会话
        QueueSession session = connection.createQueueSession(true, Session.AUTO_ACKNOWLEDGE);
        // 创建队列
        Queue queue = session.createQueue(DESTINATION);
        // 创建生产者
        QueueSender sender = session.createSender(queue);
        // 发送消息
        sendMessage(session,sender);
        // 提交会话
        session.commit();

        //关闭连接
        session.close();
        connection.close();
    }

    public static void main(String[] args) throws Exception{
        QueueSenders.run();
    }

}
